// Main JavaScript for the Smart Attendance System

// Initialize Socket.IO connection
const socket = io();

// DOM Elements
const attendanceStatus = document.getElementById('attendance-status');
const lastRecognition = document.getElementById('last-recognition');
const voiceStatus = document.getElementById('voice-status');
const voiceLogList = document.getElementById('voice-log-list');
const helpBtn = document.getElementById('help-btn');
const policyBtn = document.getElementById('policy-btn');
const leaveBtn = document.getElementById('leave-btn');

// Socket.IO event listeners
socket.on('connect', () => {
    console.log('Connected to server');
});

socket.on('disconnect', () => {
    console.log('Disconnected from server');
    attendanceStatus.textContent = '连接断开';
    attendanceStatus.classList.add('text-danger');
    voiceStatus.textContent = '连接断开';
    voiceStatus.classList.add('text-danger');
});

// Face recognition event
socket.on('face_recognition_event', (data) => {
    console.log('Face recognition event:', data);
    
    // Update attendance status
    attendanceStatus.textContent = '识别成功';
    attendanceStatus.classList.remove('text-danger');
    attendanceStatus.classList.add('text-success');
    
    // Update last recognition
    lastRecognition.textContent = `${data.name} (${data.timestamp})`;
    
    // Add to voice log
    addToVoiceLog(`识别到员工: ${data.name}`);
    
    // Reset status after 3 seconds
    setTimeout(() => {
        attendanceStatus.textContent = '等待识别';
        attendanceStatus.classList.remove('text-success', 'text-danger');
    }, 3000);
});

// Voice command event
socket.on('voice_command_event', (data) => {
    console.log('Voice command event:', data);
    
    // Update voice status
    voiceStatus.textContent = '正在处理...';
    voiceStatus.classList.remove('text-danger');
    voiceStatus.classList.add('text-info');
    
    // Add to voice log
    addToVoiceLog(`语音命令: ${data.text}`);
    
    // Reset status after 3 seconds
    setTimeout(() => {
        voiceStatus.textContent = '正在监听';
        voiceStatus.classList.remove('text-info', 'text-danger');
    }, 3000);
});

// Helper function to add entries to the voice log
function addToVoiceLog(text) {
    const li = document.createElement('li');
    const timestamp = new Date().toLocaleTimeString();
    li.innerHTML = `<span class="timestamp">${timestamp}</span> ${text}`;
    
    // Add to the beginning of the list
    voiceLogList.insertBefore(li, voiceLogList.firstChild);
    
    // Limit the number of log entries
    if (voiceLogList.children.length > 10) {
        voiceLogList.removeChild(voiceLogList.lastChild);
    }
}

// Button event listeners
helpBtn.addEventListener('click', () => {
    fetch('/api/speak', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            text: '智慧考勤系统使用说明：1. 打卡功能：请对着摄像头，系统会自动进行人脸识别并记录您的考勤。2. 请假功能：您可以通过语音申请请假，例如"我要请3天病假"。3. 制度查询：您可以通过语音查询公司制度，例如"查询考勤制度"。如需更多帮助，请联系管理员。'
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log('Help response:', data);
        addToVoiceLog('系统正在播放使用帮助');
    })
    .catch(error => {
        console.error('Error:', error);
        addToVoiceLog('播放使用帮助时出错');
    });
});

policyBtn.addEventListener('click', () => {
    fetch('/api/speak', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            text: '请问您想了解哪方面的制度？考勤制度、请假制度还是加班制度？'
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log('Policy response:', data);
        addToVoiceLog('系统正在询问您想了解的制度类型');
    })
    .catch(error => {
        console.error('Error:', error);
        addToVoiceLog('查询制度时出错');
    });
});

leaveBtn.addEventListener('click', () => {
    fetch('/api/speak', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            text: '请说明您的请假类型、时长和原因，例如"我要请3天病假，因为感冒发烧"。'
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log('Leave response:', data);
        addToVoiceLog('系统正在引导您进行请假申请');
    })
    .catch(error => {
        console.error('Error:', error);
        addToVoiceLog('请假申请时出错');
    });
});

// Initialize the application
document.addEventListener('DOMContentLoaded', () => {
    console.log('Smart Attendance System initialized');
    addToVoiceLog('系统初始化完成，等待操作...');
}); 